package managers.socialNetworkManagers;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;

import javax.swing.ImageIcon;

import managers.DBManager;

import utils.ImageUtils;
import utils.SocialUserData;


public class SocialDataUpdateMethods {

	
	public static void updateMiniatures (Connection conn, SocialNetworkManager manager) throws SQLException, IOException {
		
		HashMap<Integer, SocialUserData> users = manager.getUsers();
		ArrayList<Integer> toDownload = new ArrayList<Integer>();
		
		Statement stmt = conn.createStatement();
		String query = "select id, lastphotoupdate from spotmessenger.USERS";
		ResultSet rs = stmt.executeQuery(query);
		while (rs.next()) {
			ImageIcon image = CacheManager.retrieveImage(CacheManager.formatPersonalPhotoName(rs.getInt(1), CacheManager.SMALL), rs.getTimestamp(2));
			if (image != null) {
				users.get(rs.getInt(1)).setPhoto(image);
			} else {
				toDownload.add(rs.getInt(1));
			}	
		}
		Statement stmt2 = conn.createStatement();
		String query2 = "select id, photominiature from spotmessenger.USERS where id = "+toDownload.get(0);
		for (int i = 1; i < toDownload.size(); i++) {
			query2 += " || id ="+toDownload.get(i);
		}
		ResultSet rs2 = stmt2.executeQuery(query2);
		while (rs2.next()) {
			users.get(rs2.getInt(1)).setPhoto(ImageUtils.bytesToImage(rs2.getBytes(2), "/images/Icons/48x48/user.png"));
			if (rs2.getBytes(2) != null) {
				CacheManager.saveImage(rs2.getBytes(2), CacheManager.formatPersonalPhotoName(rs2.getInt(1), CacheManager.SMALL));
			}
		}
		DBManager.closeResources(stmt, rs);
		DBManager.closeResources(stmt2, rs2);
		SocialNetworkManager.getSharedInstance().getFeedbackManager().update();
	}
	
	
	public static void updateUsers(Connection conn, SocialNetworkManager manager) throws SQLException {
		
		Statement stmt = conn.createStatement();
		String query = "select id, nickname, mood, personalmessage from spotmessenger.USERS";
		ResultSet rs = stmt.executeQuery(query);

		while (rs.next()) {
			SocialUserData user = manager.getUser(rs.getInt(1));
			user.setNickName(rs.getString(2));
			user.setMood(rs.getString(3));
			user.setPersonalMessage(rs.getString(4));
		}
		DBManager.closeResources(stmt, rs);
		SocialNetworkManager.getSharedInstance().getFeedbackManager().update();
	}
	
}



